package fm.dongman.modellib.local;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.model.ComicDataModel;
import fm.dongman.animefm.contractlib.model.FArticleDataModel;
import fm.dongman.animefm.contractlib.model.FRankDataModel;
import fm.dongman.animefm.contractlib.model.FSheetDataModel;
import fm.dongman.animefm.contractlib.model.SearchDataModel;
import fm.dongman.modellib.DatabaseHelper;
import fm.dongman.modellib.StaticArea.StaticUrl;
import fm.dongman.modellib.model.ArticleModel;
import fm.dongman.modellib.model.BannerModel;
import fm.dongman.modellib.model.ComicModel;
import fm.dongman.modellib.model.CommentModel;
import fm.dongman.modellib.model.SheetModel;
import fm.dongman.modellib.model.SheetLabelModel;
import fm.dongman.modellib.model.UserModel;

/**
 * 数据库操作类
 * Created by KUIGE on 2017/10/11.
 */

public class DataOperationHelper {

    //单例模式，数据库操作类对象
    private static DataOperationHelper mDataOperationHelper;

    //数据库对象
    private DatabaseHelper mDatabaseHelper;

    //数据操作读取对象
    private SQLiteDatabase mSqlLiteRead;

    //数据操作写入对象
    private SQLiteDatabase mSqlLiteWritable;

    //需要创建的表
    private List<String> mList;

    /**
     * 初始化并创建数据库
     */
    private DataOperationHelper(Context context) {
        initData();
        mDatabaseHelper = new DatabaseHelper(context, mList);
        mSqlLiteRead = mDatabaseHelper.getReadableDatabase();
        mSqlLiteWritable = mDatabaseHelper.getWritableDatabase();
        addTable();
    }

    private void initData() {
        //获取数据库要创建的表
        mList = DataTable.getTable();

    }

    /**
     * @param context 实例
     * @return 返回当前操作类
     */
    public static DataOperationHelper getDataOperationHelper(Context context) {
        if (mDataOperationHelper == null) {
            mDataOperationHelper = new DataOperationHelper(context);
        }
        return mDataOperationHelper;
    }

    public static DataOperationHelper getInstance() {
        if (mDataOperationHelper != null)
            return mDataOperationHelper;
        else return null;
    }

    /**
     * 遍历所有表，创建不存在的表
     */
    private void addTable() {
        for (String s : mList) {
            mSqlLiteWritable.execSQL(s);
        }
    }

    /**
     * 遍历表
     */
    private int tables() {
        int number = 0;
        Cursor cursor = mSqlLiteRead.rawQuery("select name from sqlite_master where type='table';", null);
        while (cursor.moveToNext()) {
            //遍历出表名
            String name = cursor.getString(0);
            Log.e("System.out", name);
        }
        cursor.close();
        return number;
    }

    /**
     * 将热门搜索和搜索历史存入数据库
     */
    void addSearchHotWords(SearchDataModel dataModel) {
        List<String> mHots = dataModel.getHotSearchList();
        List<String> mPast = dataModel.getHistorySearchList();
        mSqlLiteWritable.execSQL("update " + ConstFlags.SearchHotWords.TABLE + " set " + ConstFlags.SearchHotWords.HOT_SEARCH + "=null");
        ContentValues values = new ContentValues();
        int x = 0;
        if (dataModel.getHistorySearchList().size() >= dataModel.getHotSearchList().size()) {
            x = dataModel.getHistorySearchList().size();
        } else {
            x = dataModel.getHotSearchList().size();
        }
        for (int y = 0; y < x; y++) {
            if (mHots.get(y) != null) {
                values.put(ConstFlags.SearchHotWords.HOT_SEARCH, mHots.get(y));
            }
            if (mPast.get(y) != null) {
                values.put(ConstFlags.SearchHotWords.HOT_PAST, mPast.get(y));
            }
            mSqlLiteWritable.insert(ConstFlags.SearchHotWords.TABLE, null, values);
            values.clear();
        }
    }

    /**
     * 最新番剧
     */
    void addComic_newComics(List<IModel.IComicModel> models) {
        mSqlLiteWritable.execSQL("delete from " + ConstFlags.ComicComics.TABLE);
        ContentValues values = new ContentValues();
        for (IModel.IComicModel e : models) {
            ComicModel model = (ComicModel) e;
            values.put(ConstFlags.ComicComics.IMG_URL, model.getImgUrl());
            values.put(ConstFlags.ComicComics.CREATE_TIME, model.getYear());
            values.put(ConstFlags.ComicComics.EPISODES, model.getEpisodes());
            values.put(ConstFlags.ComicComics.SUBJECT_ID, model.getId());
            values.put(ConstFlags.ComicComics.TITLE, model.getTitle());
            values.put(ConstFlags.ComicComics.GENRE, model.getGenre());
            values.put(ConstFlags.ComicComics.DIRECTOR, model.getDirector());
            mSqlLiteWritable.insert(ConstFlags.ComicComics.TABLE, null, values);
            values.clear();
        }
    }

    /**
     * 推荐
     */
    void addComic_recommendComics(List<IModel.IComicModel> models) {
        mSqlLiteWritable.execSQL("delete from " + ConstFlags.ComicRecommendComics.TABLE);
        ContentValues values = new ContentValues();
        for (IModel.IComicModel e : models) {
            ComicModel model = (ComicModel) e;
            values.put(ConstFlags.ComicRecommendComics.UPTIME, model.getYear());
            values.put(ConstFlags.ComicRecommendComics.IMG_URL, model.getImgUrl());
            values.put(ConstFlags.ComicRecommendComics.RATE, model.getRateScore());
            values.put(ConstFlags.ComicRecommendComics.SUBJECT_ID, model.getId());
            values.put(ConstFlags.ComicRecommendComics.SUBJECT_NAME, model.getTitle());
            mSqlLiteWritable.insert(ConstFlags.ComicRecommendComics.TABLE, null, values);
            values.clear();
        }
    }

    /**
     * 吐槽
     */
    void addComic_newComment(List<IModel.ICommentModel> models) {
        mSqlLiteWritable.execSQL("delete from " + ConstFlags.ComicNewComment.TABLE);
        ContentValues values = new ContentValues();
        for (IModel.ICommentModel e : models) {
            CommentModel model = (CommentModel) e;
            values.put(ConstFlags.ComicNewComment.AVATAR_URL, model.getAvatarUrl());
            values.put(ConstFlags.ComicNewComment.CONTENT, model.getContent());
            values.put(ConstFlags.ComicNewComment.CREATE_TIME, model.getCreateTime());
            values.put(ConstFlags.ComicNewComment.SUBJECT_ID, model.getSubjectId());
            values.put(ConstFlags.ComicNewComment.TITLE, model.getTitle());
            values.put(ConstFlags.ComicNewComment.USER_ID, model.getUserId());
            values.put(ConstFlags.ComicNewComment.USERNAME, model.getUserName());
            addComment_User(model.getUser());
            mSqlLiteWritable.insert(ConstFlags.ComicNewComment.TABLE, null, values);
            values.clear();
        }
    }

    /**
     * @param userModel 添加最新槽点中的用户信息
     */
    private void addComment_User(IModel.IUserModel userModel)
    {
        mSqlLiteWritable.execSQL("delete from " + "comment_user");
        ContentValues values = new ContentValues();
        UserModel model = (UserModel) userModel;
        values.put(ConstFlags.User.AVATARURL,model.getAvatarUrl());
        values.put(ConstFlags.User.GUANZHU,model.getGender());
        values.put(ConstFlags.User.USERNAME,model.getUserName());
        values.put(ConstFlags.User.USERID,model.getUserId());
        mSqlLiteWritable.insert("comment_user",null,values);
        values.clear();
    }

    /**
     * 添加hot表
     */
    void addFArticleHot(List<IModel.IArticleModel> models) {
        mSqlLiteWritable.execSQL("delete from farticle_hot");
        ContentValues values = new ContentValues();
        for (IModel.IArticleModel e : models) {
            ArticleModel model = (ArticleModel) e;
            values.put(ConstFlags.FArticleHot.TITLE, model.getTitle());
            values.put(ConstFlags.FArticleHot.ID, model.getArticleId());
            values.put(ConstFlags.FArticleHot.CONTEXT, model.getSummary());
            values.put(ConstFlags.FArticleHot.BROWSE_COUNT, model.getBrowseCount());
            values.put(ConstFlags.FArticleHot.CREATE_TIME, model.getCreateTime());
            values.put(ConstFlags.FArticleHot.IMG_URL, model.getImgUrl());
            mSqlLiteWritable.insert("farticle_hot", null, values);
            values.clear();
        }
    }

    /**
     * 添加 banner表
     */
    void addFArticleBanner(List<IModel.IArticleModel> models) {
        mSqlLiteWritable.execSQL("delete from farticle_banner");
        ContentValues values = new ContentValues();
        for (IModel.IArticleModel e : models) {
            ArticleModel model = (ArticleModel) e;
            values.put(ConstFlags.FArticleBanner.ID, model.getArticleId());
            values.put(ConstFlags.FArticleBanner.IMG_URL, model.getImgUrl());
            values.put(ConstFlags.FArticleBanner.TITLE, model.getTitle());
            mSqlLiteWritable.insert("farticle_banner", null, values);
            values.clear();
        }
    }

    /**
     * 添加最新文章表
     */
    void addFArticleNew(List<IModel.IArticleModel> models) {
        mSqlLiteWritable.execSQL("delete from farticle_new");
        ContentValues values = new ContentValues();

        for (IModel.IArticleModel e : models) {
            ArticleModel model = (ArticleModel) e;
            values.put(ConstFlags.FArticleNew.USER_ID, model.getArticleId());
            values.put(ConstFlags.FArticleNew.TITLE, model.getTitle());
            values.put(ConstFlags.FArticleNew.CONTENT, model.getSummary());
            values.put(ConstFlags.FArticleNew.IMG_URL, model.getImgUrl());
            mSqlLiteWritable.insert("farticle_new", null, values);
            values.clear();
        }
    }

    /**
     * 专题列表
     */
    void addFSheetSpec(List<IModel.ISheetModel> models) {
        mSqlLiteWritable.execSQL("delete from fmandan_spec");
        ContentValues values = new ContentValues();
        for (IModel.ISheetModel e : models) {
            SheetModel model = (SheetModel) e;
            values.put(ConstFlags.fMandan_Spec.BANGUMICOUNT, model.getBangumiCount());
            values.put(ConstFlags.fMandan_Spec.BROWSECOUNT, model.getBrowseCount());
            values.put(ConstFlags.fMandan_Spec.COLLECTCOUNT, model.getCollectCount());
            values.put(ConstFlags.fMandan_Spec.CREATE_TIME, model.getCreateTime());
            values.put(ConstFlags.fMandan_Spec.SUMMARY, model.getSummary());
            values.put(ConstFlags.fMandan_Spec.TOPICID, model.getMandanId());
            values.put(ConstFlags.fMandan_Spec.TOPICIMG, model.getMandanImg());
            values.put(ConstFlags.fMandan_Spec.TOPICTITLE, model.getMandanTitle());
            mSqlLiteWritable.insert(ConstFlags.fMandan_Spec.TABLE, null, values);
            values.clear();
        }
    }

    /**
     * 添加漫单标签到数据库
     */
    void addFSheetTopic(List<IModel.ISheetLabelModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from fmandan_tag");
            ContentValues values = new ContentValues();
            for (IModel.ISheetLabelModel e : models) {
                SheetLabelModel model = (SheetLabelModel) e;
                values.put(ConstFlags.fMandan_Tag.TAGID, model.getTagId());
                values.put(ConstFlags.fMandan_Tag.TAGNAME, model.getTagName());
                values.put(ConstFlags.fMandan_Tag.TAGIMG, model.getTagImg());
                mSqlLiteWritable.insert(ConstFlags.fMandan_Tag.TABLE, null, values);
                values.clear();
            }
        }
    }

    /**
     * 添加到数据库漫单_达人
     */
    void addFSheetDaren(List<IModel.IUserModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from fmandan_daren");
            ContentValues values = new ContentValues();
            for (IModel.IUserModel e : models) {
                UserModel model = (UserModel) e;
                values.put(ConstFlags.fMandan_daren.MMANDANCOUNT, model.getSheetCount());
                values.put(ConstFlags.fMandan_daren.MAVATARURL, model.getAvatarUrl());
                values.put(ConstFlags.fMandan_daren.MUSERID, model.getUserId());
                values.put(ConstFlags.fMandan_daren.MUSERNAME, model.getUserName());
                mSqlLiteWritable.insert(ConstFlags.fMandan_daren.TABLE, null, values);
                values.clear();
            }
        }
    }

    /**
     * 添加漫单列表到数据库
     */
    void addFSheetList(List<IModel.ISheetModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from fmandan_list");
            ContentValues values = new ContentValues();
            for (IModel.ISheetModel e : models) {
                SheetModel model = (SheetModel) e;
                values.put(ConstFlags.fMandan_list.AVATARURL, model.getAvatarUrl());
                values.put(ConstFlags.fMandan_list.BANGUMICOUNT, model.getBangumiCount());
                values.put(ConstFlags.fMandan_list.MANDANID, model.getMandanId());
                values.put(ConstFlags.fMandan_list.MANDANIMG, model.getMandanImg());
                values.put(ConstFlags.fMandan_list.MANDANTITLE, model.getMandanTitle());
                values.put(ConstFlags.fMandan_list.USERID, model.getUserId());
                values.put(ConstFlags.fMandan_list.USERNAME, model.getUser().getUserName());
                mSqlLiteWritable.insert(ConstFlags.fMandan_list.TABLE, null, values);
            }
        }
    }

    /**
     * 将数据保存到数据库中
     *
     * @param models 文章数据模型
     */
    void addArticleData(List<IModel.IArticleModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from article");
            ContentValues values = new ContentValues();
            for (IModel.IArticleModel e : models) {
                ArticleModel a = (ArticleModel) e;
                values.put(ConstFlags.Article.ARTICLE, a.getArticleId());
                values.put(ConstFlags.Article.BROWSECOUNT, a.getBrowseCount());
                values.put(ConstFlags.Article.COMMENTCOUNT, a.getCommentCount());
                values.put(ConstFlags.Article.CREATETIME, a.getCreateTime());
                values.put(ConstFlags.Article.IMGURL, a.getImgUrl());
                values.put(ConstFlags.Article.SUMMARY, a.getSummary());
                values.put(ConstFlags.Article.TITLE, a.getTitle());
                mSqlLiteWritable.insert("article", null, values);
                values.clear();
            }
        }
    }

    /**
     * 删除数据库中用户的所有数据
     */
    public void deleteUser() {
        mSqlLiteWritable.execSQL("delete from user");
        StaticUrl.TOKEN_KEY = "";
        StaticUrl.RETOKEN_KEY = "";
    }

    /**
     * 将用户信息保存在数据库
     */
    void addUser(List<IModel.IUserModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from user");
            ContentValues values = new ContentValues();
            for (IModel.IUserModel e : models) {
                UserModel model = (UserModel) e;
                values.put(ConstFlags.User.USERNAME, model.getUserName());
                values.put(ConstFlags.User.USERID, model.getUserId());
                values.put(ConstFlags.User.USERFANSNUM, model.getFansNum());
                values.put(ConstFlags.User.USERSUMMARY, model.getDescription());
                values.put(ConstFlags.User.AVATARURL, model.getAvatarUrl());
                values.put(ConstFlags.User.TOKEN, model.getToken());
                values.put(ConstFlags.User.UPTOKEN, model.getRefreshToken());
                values.put(ConstFlags.User.MESSAGE, model.getMessageNum());
                values.put(ConstFlags.User.GUANZHU, model.getFlowNum());
                mSqlLiteWritable.insert(ConstFlags.User.TABLE, null, values);
                values.clear();
            }
        }
    }

    void saveToken(JSONObject object)
    {
        if (object != null){
            try {
                String token = object.getJSONObject("data").getString("token");
                ContentValues values = new ContentValues();
                values.put(ConstFlags.User.TOKEN,token);
                StaticUrl.TOKEN_KEY = token;
                token = object.getJSONObject("data").getString("refresh_token");
                values.put(ConstFlags.User.UPTOKEN,token);
                StaticUrl.RETOKEN_KEY =token;
                mSqlLiteWritable.update(ConstFlags.User.TABLE,values,null,null);
                values.clear();
                Log.e("tokens",StaticUrl.TOKEN_KEY+"  "+StaticUrl.RETOKEN_KEY);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 将轮播数据保存在数据库中
     *
     * @param models 轮播数据模型
     */
    void addBanner(List<IModel.IBannerModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from banner");
            ContentValues values = new ContentValues();
            for (IModel.IBannerModel e : models) {
                BannerModel b = (BannerModel) e;
                values.put(ConstFlags.Banner.ARTICLE, b.getArticleId());
                values.put(ConstFlags.Banner.IMGURL, b.getImgUrl());
                values.put(ConstFlags.Banner.SUBJECTID, b.getSubjectId());
                values.put(ConstFlags.Banner.TITLE, b.getTitle());
                mSqlLiteWritable.insert(ConstFlags.Banner.TABLE, null, values);
                values.clear();
            }
        }
    }

    /**
     * @param models 人气番剧
     */
    void addRankComic(List<IModel.IComicModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from rankComic");
            ContentValues values = new ContentValues();
            for (IModel.IComicModel e : models) {
                ComicModel b = (ComicModel) e;
                values.put(ConstFlags.RankComic.TITLE, b.getTitle());
                values.put(ConstFlags.RankComic.SUBJECTID, b.getId());
                values.put(ConstFlags.RankComic.IMGURL, b.getImgUrl());
                values.put(ConstFlags.RankComic.RATECORE, b.getRateScore());
                mSqlLiteWritable.insert(ConstFlags.RankComic.TABLE, null, values);
                values.clear();
            }
        }
    }

    /**
     * 将动漫数据保存到数据库
     *
     * @param models 动漫数据模型
     */
    void addComic(List<IModel.IComicModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from comic");
            ContentValues values = new ContentValues();
            for (IModel.IComicModel e : models) {
                ComicModel b = (ComicModel) e;
                values.put(ConstFlags.Comic.TITLE, b.getTitle());
                values.put(ConstFlags.Comic.SUBJECTID, b.getId());
                values.put(ConstFlags.Comic.IMGURL, b.getImgUrl());
                values.put(ConstFlags.Comic.RATESCORE, b.getRateScore());
                mSqlLiteWritable.insert(ConstFlags.Comic.TABLE, null, values);
                values.clear();
            }
        }
    }

    /**
     * 存入数据库
     *
     * @param models 评论
     */
    void addComment(List<IModel.ICommentModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from comment");
            ContentValues values = new ContentValues();
            for (IModel.ICommentModel e : models) {
                CommentModel c = (CommentModel) e;
                values.put(ConstFlags.Comment.USERID, c.getUser().getUserId());
                values.put(ConstFlags.Comment.USERNAME, c.getUser().getUserName());
                values.put(ConstFlags.Comment.SEX, c.getUser().getGender());
                values.put(ConstFlags.Comment.AVATARURL, c.getUser().getAvatarUrl());
                values.put(ConstFlags.Comment.CONTENT, c.getContent());
                values.put(ConstFlags.Comment.CREATETIME, c.getCreateTime());
                values.put(ConstFlags.Comment.TIME, c.getTime());
                values.put(ConstFlags.Comment.SUMMARY, c.getSummary());
                mSqlLiteWritable.insert(ConstFlags.Comment.TABLE, null, values);
                values.clear();
            }
        }
    }

    /**
     * 存入数据库
     *
     * @param models 漫单
     */
    void addSheet(List<IModel.ISheetModel> models) {
        if (models != null) {
            mSqlLiteWritable.execSQL("delete from sheet");
            ContentValues values = new ContentValues();
            for (IModel.ISheetModel e : models) {
                SheetModel s = (SheetModel) e;
                values.put(ConstFlags.Sheet.CREATETIME, s.getCreateTime());
                values.put(ConstFlags.Sheet.MANDANTITLE, s.getMandanTitle());
                values.put(ConstFlags.Sheet.MANDANID, s.getMandanId());
                values.put(ConstFlags.Sheet.AVATARURL, s.getUser().getAvatarUrl());
                values.put(ConstFlags.Sheet.USERID, s.getUser().getUserId());
                values.put(ConstFlags.Sheet.USERNAME, s.getUser().getUserName());
                values.put(ConstFlags.Sheet.NUM, s.getNum());
                values.put(ConstFlags.Sheet.SUMMARY, s.getSummary());
                mSqlLiteWritable.insert(ConstFlags.Sheet.TABLE, null, values);
                values.clear();
            }
        }
    }

    /**
     * @return 从数据库获取数据
     */
    public IModel.IUserModel downUser() {
        UserModel model = new UserModel();
        Cursor cursor = mSqlLiteRead.query(ConstFlags.User.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                model.setUserName(cursor.getString(cursor.getColumnIndex(ConstFlags.User.USERNAME)));
                model.setUserId(cursor.getString(cursor.getColumnIndex(ConstFlags.User.USERID)));
                model.setDescription(cursor.getString(cursor.getColumnIndex(ConstFlags.User.USERSUMMARY)));
                model.setFansNum(cursor.getString(cursor.getColumnIndex(ConstFlags.User.USERFANSNUM)));
                model.setAvatarUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.User.AVATARURL)));
                model.setFlowNum(cursor.getString(cursor.getColumnIndex(ConstFlags.User.GUANZHU)));
                model.setMessageNum(cursor.getString(cursor.getColumnIndex(ConstFlags.User.MESSAGE)));
                model.setToken(cursor.getString(cursor.getColumnIndex(ConstFlags.User.TOKEN)));
                model.setRefreshToken(cursor.getString(cursor.getColumnIndex(ConstFlags.User.UPTOKEN)));
                StaticUrl.TOKEN_KEY = model.getToken();
                StaticUrl.RETOKEN_KEY = model.getRefreshToken();

            } while (cursor.moveToNext());
        }
        cursor.close();
        return model;
    }

    /**
     * @return 从数据库中获取到的数据
     */
    List<IModel.IArticleModel> downArticleData() {
        List<IModel.IArticleModel> models = new ArrayList<>();
        ArticleModel model;
        Cursor cursor = mSqlLiteRead.query(ConstFlags.Article.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                model = new ArticleModel();
                model.setArticleId(cursor.getString(cursor.getColumnIndex(ConstFlags.Article.ARTICLE)));
                model.setBrowseCount(cursor.getString(cursor.getColumnIndex(ConstFlags.Article.BROWSECOUNT)));
                model.setCommentCount(cursor.getString(cursor.getColumnIndex(ConstFlags.Article.COMMENTCOUNT)));
                model.setCreateTime(cursor.getString(cursor.getColumnIndex(ConstFlags.Article.CREATETIME)));
                model.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.Article.IMGURL)));
                model.setSummary(cursor.getString(cursor.getColumnIndex(ConstFlags.Article.SUMMARY)));
                model.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.Article.TITLE)));
                models.add(model);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return models;
    }

    /**
     * @return 从数据库中获取轮播数据
     */
    List<IModel.IBannerModel> downBannerData() {
        List<IModel.IBannerModel> models = new ArrayList<>();
        BannerModel model;
        Cursor cursor = mSqlLiteRead.query(ConstFlags.Banner.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                model = new BannerModel();
                model.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.Banner.TITLE)));
                model.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.Banner.IMGURL)));
                model.setSubjectId(cursor.getString(cursor.getColumnIndex(ConstFlags.Banner.SUBJECTID)));
                model.setArticleId(cursor.getString(cursor.getColumnIndex(ConstFlags.Banner.ARTICLE)));
                models.add(model);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return models;
    }

    /**
     * @return 获取动漫数据
     */
    List<IModel.IComicModel> downComicData() {
        List<IModel.IComicModel> models = new ArrayList<>();
        ComicModel model;
        Cursor cursor = mSqlLiteRead.query(ConstFlags.Comic.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                model = new ComicModel();
                model.setId(cursor.getString(cursor.getColumnIndex(ConstFlags.Comic.SUBJECTID)));
                model.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.Comic.IMGURL)));
                model.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.Comic.TITLE)));
                model.setRateScore(cursor.getString(cursor.getColumnIndex(ConstFlags.Comic.RATESCORE)));
                models.add(model);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return models;
    }

    /**
     * @return 获取人气番剧
     */
    List<IModel.IComicModel> downRankComicData() {
        List<IModel.IComicModel> models = new ArrayList<>();
        ComicModel model;
        Cursor cursor = mSqlLiteRead.query(ConstFlags.RankComic.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                model = new ComicModel();
                model.setId(cursor.getString(cursor.getColumnIndex(ConstFlags.RankComic.SUBJECTID)));
                model.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.RankComic.IMGURL)));
                model.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.RankComic.TITLE)));
                model.setRateScore(cursor.getString(cursor.getColumnIndex(ConstFlags.RankComic.RATECORE)));
                models.add(model);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return models;
    }


    /**
     * @return 获取评论数据
     */
    List<IModel.ICommentModel> downCommentData() {
        List<IModel.ICommentModel> models = new ArrayList<>();
        CommentModel model;
        Cursor cursor = mSqlLiteRead.query(ConstFlags.Comment.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                model = new CommentModel();
                UserModel userModel = new UserModel();
                userModel.setAvatarUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.Comment.AVATARURL)));
                userModel.setGender(cursor.getString(cursor.getColumnIndex(ConstFlags.Comment.SEX)));
                userModel.setUserId(cursor.getString(cursor.getColumnIndex(ConstFlags.Comment.USERID)));
                userModel.setUserName(cursor.getString(cursor.getColumnIndex(ConstFlags.Comment.USERNAME)));
                model.setUser(userModel);
                model.setContent(cursor.getString(cursor.getColumnIndex(ConstFlags.Comment.CONTENT)));
                model.setCreateTime(cursor.getString(cursor.getColumnIndex(ConstFlags.Comment.CREATETIME)));
                model.setSummary(cursor.getString(cursor.getColumnIndex(ConstFlags.Comment.SUMMARY)));
                model.setTime(cursor.getString(cursor.getColumnIndex(ConstFlags.Comment.TIME)));
                models.add(model);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return models;
    }

    /**
     * @return 获取漫单数据
     */
    List<IModel.ISheetModel> downSheetData() {
        List<IModel.ISheetModel> models = new ArrayList<>();
        SheetModel model;
        Cursor cursor = mSqlLiteRead.query(ConstFlags.Sheet.TABLE, null, null, null, null, null, null);
        while (cursor.moveToNext()) {
            model = new SheetModel();
            UserModel userModel = new UserModel();
            userModel.setUserName(cursor.getString(cursor.getColumnIndex(ConstFlags.Sheet.USERNAME)));
            userModel.setUserId(cursor.getString(cursor.getColumnIndex(ConstFlags.Sheet.USERID)));
            userModel.setAvatarUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.Sheet.AVATARURL)));
            model.setUser(userModel);
            model.setSummary(cursor.getString(cursor.getColumnIndex(ConstFlags.Sheet.SUMMARY)));
            model.setCreateTime(cursor.getString(cursor.getColumnIndex(ConstFlags.Sheet.CREATETIME)));
            model.setMandanId(cursor.getString(cursor.getColumnIndex(ConstFlags.Sheet.MANDANID)));
            model.setMandanTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.Sheet.MANDANTITLE)));
            model.setNum(cursor.getString(cursor.getColumnIndex(ConstFlags.Sheet.NUM)));
            models.add(model);
        }
        cursor.close();
        return models;
    }


    /**
     * 从数据库解析漫单数据
     */
    FSheetDataModel downSheetDataModel() {
        FSheetDataModel models = new FSheetDataModel();
        Cursor cursor;

        cursor = mSqlLiteRead.query(ConstFlags.fMandan_daren.TABLE, null, null, null, null, null, null);
        List<IModel.IUserModel> masters = new ArrayList<>();
        UserModel user;
        if (cursor.moveToFirst()) {
            do {
                user = new UserModel();
                user.setAvatarUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_daren.MAVATARURL)));
                user.setSheetCount(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_daren.MMANDANCOUNT)));
                user.setUserId(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_daren.MUSERID)));
                user.setUserName(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_daren.MUSERNAME)));
                masters.add(user);
            } while (cursor.moveToNext());
        }

        cursor = mSqlLiteRead.query(ConstFlags.fMandan_list.TABLE, null, null, null, null, null, null);
        List<IModel.ISheetModel> sheets = new ArrayList<>();
        SheetModel she;
        if (cursor.moveToFirst()) {
            do {
                she = new SheetModel();
                she.setAvatarUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_list.AVATARURL)));
                she.setBangumiCount(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_list.BANGUMICOUNT)));
                she.setMandanId(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_list.MANDANID)));
                she.setMandanImg(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_list.MANDANIMG)));
                she.setMandanTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_list.MANDANTITLE)));
                UserModel userModel = new UserModel();
                userModel.setUserId(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_list.USERID)));
                userModel.setUserName(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_list.USERNAME)));
                she.setUser(userModel);
                sheets.add(she);
            } while (cursor.moveToNext());
        }

        cursor = mSqlLiteRead.query(ConstFlags.fMandan_Tag.TABLE, null, null, null, null, null, null);
        List<IModel.ISheetLabelModel> tags = new ArrayList<>();
        SheetLabelModel tag;
        if (cursor.moveToFirst()) {
            do {
                tag = new SheetLabelModel();
                tag.setTagId(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Tag.TAGID)));
                tag.setTagImg(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Tag.TAGIMG)));
                tag.setTagName(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Tag.TAGNAME)));
                tags.add(tag);
            } while (cursor.moveToNext());
        }

        cursor = mSqlLiteRead.query(ConstFlags.fMandan_Spec.TABLE, null, null, null, null, null, null);
        List<IModel.ISheetModel> specials = new ArrayList<>();
        SheetModel spec;
        if (cursor.moveToFirst()) {
            do {
                spec = new SheetModel();
                spec.setBangumiCount(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Spec.BANGUMICOUNT)));
                spec.setBrowseCount(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Spec.BROWSECOUNT)));
                spec.setCollectCount(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Spec.COLLECTCOUNT)));
                spec.setCreateTime(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Spec.CREATE_TIME)));
                spec.setSummary(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Spec.SUMMARY)));
                spec.setMandanId(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Spec.TOPICID)));
                spec.setMandanImg(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Spec.TOPICIMG)));
                spec.setMandanTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.fMandan_Spec.TOPICTITLE)));
                specials.add(spec);
            } while (cursor.moveToNext());
        }

        cursor.close();
        models.setMLabels(tags);
        models.setSpecials(specials);
        models.setSheets(sheets);
        models.setMasters(masters);
        return models;
    }

    //解析漫圈列表数据
    FArticleDataModel downFarticle() {
        FArticleDataModel FArticle = new FArticleDataModel();
        Cursor cursor;

        //最火hot列表
        ArticleModel Hot;
        List<IModel.IArticleModel> ListHot = new ArrayList<>();
        cursor = mSqlLiteRead.query("farticle_hot", null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                Hot = new ArticleModel();
                Hot.setArticleId(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleHot.ID)));
                Hot.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleHot.TITLE)));
                Hot.setSummary(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleHot.CONTEXT)));
                Hot.setBrowseCount(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleHot.BROWSE_COUNT)));
                Hot.setCreateTime(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleHot.CREATE_TIME)));
                Hot.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleHot.IMG_URL)));
                ListHot.add(Hot);
            } while (cursor.moveToNext());
        }


        //文章Article列表
        List<IModel.IArticleModel> ListNewArticle = new ArrayList<>();
        ArticleModel NewArticle;
        cursor = mSqlLiteRead.query("farticle_new", null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                NewArticle = new ArticleModel();
                NewArticle.setArticleId(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleNew.USER_ID)));
                NewArticle.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleNew.TITLE)));
                NewArticle.setSummary(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleNew.CONTENT)));
                NewArticle.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleNew.IMG_URL)));
                ListNewArticle.add(NewArticle);
            } while (cursor.moveToNext());
        }

        //banner列表
        List<IModel.IArticleModel> ListBanner = new ArrayList<>();
        ArticleModel banner;
        cursor = mSqlLiteRead.query("farticle_banner", null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                banner = new ArticleModel();
                banner.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleBanner.IMG_URL)));
                banner.setArticleId(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleBanner.ID)));
                banner.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.FArticleBanner.TITLE)));
                ListBanner.add(banner);
            } while (cursor.moveToNext());
        }

        cursor.close();

        FArticle.setNewArticles(ListNewArticle);
        FArticle.setDynamicArticles(ListBanner);
        FArticle.setHotArticles(ListHot);

        return FArticle;
    }

    /**
     * 解析番剧
     */
    ComicDataModel downComicDatas() {
        ComicDataModel model = new ComicDataModel();
        ComicModel comicModel;
        CommentModel commentModel;
        Cursor cursor;

        List<IModel.IComicModel> Comic_Comics = new ArrayList<>();      //最新番剧
        cursor = mSqlLiteRead.query(ConstFlags.ComicComics.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                comicModel = new ComicModel();
                comicModel.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicComics.TITLE)));
                comicModel.setId(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicComics.SUBJECT_ID)));
                comicModel.setYear(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicComics.CREATE_TIME)));
                comicModel.setEpisodes(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicComics.EPISODES)));
                comicModel.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicComics.IMG_URL)));
                comicModel.setGenre(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicComics.GENRE)));
                comicModel.setDirector(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicComics.DIRECTOR)));
                Comic_Comics.add(comicModel);
            } while (cursor.moveToNext());
        }

        cursor = mSqlLiteRead.query(ConstFlags.ComicRecommendComics.TABLE, null, null, null, null, null, null);
        List<IModel.IComicModel> Comic_RecommendComics = new ArrayList<>(); //新番推荐
        if (cursor.moveToFirst()) {
            do {
                comicModel = new ComicModel();
                comicModel.setImgUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicRecommendComics.IMG_URL)));
                comicModel.setYear(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicRecommendComics.UPTIME)));
                comicModel.setRateScore(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicRecommendComics.RATE)));
                comicModel.setId(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicRecommendComics.SUBJECT_ID)));
                comicModel.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicRecommendComics.SUBJECT_NAME)));
                Comic_RecommendComics.add(comicModel);
            } while (cursor.moveToNext());
        }

        cursor = mSqlLiteRead.query(ConstFlags.ComicNewComment.TABLE, null, null, null, null, null, null);
        List<IModel.ICommentModel> newComment = new ArrayList<>();      //吐槽
        if (cursor.moveToFirst()) {
            do {
                commentModel = new CommentModel();
                commentModel.setTitle(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicNewComment.TITLE)));
                commentModel.setAvatarUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicNewComment.AVATAR_URL)));
                commentModel.setContent(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicNewComment.CONTENT)));
                commentModel.setCreateTime(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicNewComment.CREATE_TIME)));
                commentModel.setSubjectId(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicNewComment.SUBJECT_ID)));
                commentModel.setUserId(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicNewComment.USER_ID)));
                commentModel.setUserName(cursor.getString(cursor.getColumnIndex(ConstFlags.ComicNewComment.USERNAME)));
                commentModel.setUser(downCommentUser());
                newComment.add(commentModel);
            } while (cursor.moveToNext());
        }
        cursor.close();
        model.setNewComment(newComment);
        model.setRecommendComics(Comic_RecommendComics);
        model.setNewComics(Comic_Comics);
        return model;
    }

    /**
     * @return 解析最新槽点中的用户信息
     */
    private UserModel downCommentUser()
    {
        UserModel model = new UserModel();
        Cursor cursor = mSqlLiteRead.query("comment_user",null,null,null,null,null,null);
        if (cursor.moveToFirst())
        {
            do {
                model.setUserName(cursor.getString(cursor.getColumnIndex(ConstFlags.User.USERNAME)));
                model.setUserId(cursor.getString(cursor.getColumnIndex(ConstFlags.User.USERID)));
                model.setAvatarUrl(cursor.getString(cursor.getColumnIndex(ConstFlags.User.AVATARURL)));
                model.setGender(cursor.getString(cursor.getColumnIndex(ConstFlags.User.GUANZHU)));
            }while (cursor.moveToNext());
        }
        cursor.close();
        return model;
    }

    /**
     * 从数据库解析搜索
     */
    SearchDataModel downSearchHotWords() {
        SearchDataModel model = new SearchDataModel();
        List<String> mList = new ArrayList<>();
        Cursor cursor = mSqlLiteRead.query(ConstFlags.SearchHotWords.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                if (cursor.getString(cursor.getColumnIndex(ConstFlags.SearchHotWords.HOT_SEARCH)).length() == 0) {
                    break;
                }
                mList.add(cursor.getString(cursor.getColumnIndex(ConstFlags.SearchHotWords.HOT_SEARCH)));
            } while (cursor.moveToNext());
        }
        model.setHotSearchList(mList);
//        cursor = mSqlLiteRead.query(ConstFlags.SearchKey.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                if (cursor.getString(cursor.getColumnIndex(ConstFlags.SearchHotWords.HOT_PAST)).length() == 0) {
                    break;
                }
                mList.add(cursor.getString(cursor.getColumnIndex(ConstFlags.SearchHotWords.HOT_PAST)));
            } while (cursor.moveToNext());
        }
        model.setHistorySearchList(mList);
        cursor.close();
        return model;
    }

    /**
     * @param key 将关键字保存到数据库
     */
    public void saveSearchKey(String key) {
//        List<String> Kets = obtainSearchKeys();
//        if (Kets !=null) {
//            for (int i = 0; i < Kets.size(); i++) {
//                if (Kets.get(i).equals(key)) {
//                    return;
//                }
//            }
//        }
        Log.e("num",key);
        ContentValues values = new ContentValues();
        values.put(ConstFlags.SearchKey.WORD, key);
        mSqlLiteWritable.insert(ConstFlags.SearchKey.TABLE, null, values);
        values.clear();
    }

    /**
     * 从数据库获取关键字
     */
    public List<String> obtainSearchKeys() {
        List<String> list = new ArrayList<>();
        Cursor cursor = mSqlLiteRead.query(ConstFlags.SearchKey.TABLE, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                if (cursor.getString(cursor.getColumnIndex(ConstFlags.SearchKey.WORD)).length() == 0) {
                    break;
                }
                list.add(cursor.getString(cursor.getColumnIndex(ConstFlags.SearchKey.WORD)));
            } while (cursor.moveToNext());
        }
        cursor.close();
        return list;
    }


    /**
     * @param dataModel 保存发现页面的漫榜数据
     */
    void saveFRank(FRankDataModel dataModel) {
        setFRanList(dataModel.getWeekHotComicRank(),ConstFlags.fManbang_Hot.TABLE,ConstFlags.fManbang_Hot.TITLE,ConstFlags.fManbang_Hot.SUBJECT_ID);
        setFRanList(dataModel.getComicTopRank(),ConstFlags.fManbang_xinfan.TABLE,ConstFlags.fManbang_xinfan.TITLE,ConstFlags.fManbang_xinfan.SUBJECT_ID);
        setFRanList(dataModel.getDomesticComicRank(),ConstFlags.fManbang_guochan.TABLE,ConstFlags.fManbang_guochan.TITLE,ConstFlags.fManbang_guochan.SUBJECT_ID);
        setFRanList(dataModel.getHaremComicRank(),ConstFlags.fManbang_hougong.TABLE,ConstFlags.fManbang_hougong.TITLE,ConstFlags.fManbang_hougong.SUBJECT_ID);
    }

    private void setFRanList(List<IModel.IComicModel> models, String table, String title, String id)
    {

        mSqlLiteWritable.execSQL("delete from " + table);
        ContentValues values = new ContentValues();
        ComicModel model;
        for (IModel.IComicModel comicModel : models) {
            model = (ComicModel) comicModel;
            values.put(id, model.getId());
            values.put(title, model.getTitle());
            mSqlLiteWritable.insert(table, null, values);
            values.clear();
        }
    }

    /**
     * @return 获取数据库中的发现页面的漫榜数据
     */
    FRankDataModel downFRank() {
        FRankDataModel dataModel = new FRankDataModel();
        dataModel.setWeekHotComicRank(getFRankList(ConstFlags.fManbang_Hot.TABLE,ConstFlags.fManbang_Hot.TITLE,ConstFlags.fManbang_Hot.SUBJECT_ID));
        dataModel.setComicTopRank(getFRankList(ConstFlags.fManbang_xinfan.TABLE,ConstFlags.fManbang_xinfan.TITLE,ConstFlags.fManbang_xinfan.SUBJECT_ID));
        dataModel.setDomesticComicRank(getFRankList(ConstFlags.fManbang_guochan.TABLE,ConstFlags.fManbang_guochan.TITLE,ConstFlags.fManbang_guochan.SUBJECT_ID));
        dataModel.setHaremComicRank(getFRankList(ConstFlags.fManbang_hougong.TABLE,ConstFlags.fManbang_hougong.TITLE,ConstFlags.fManbang_hougong.SUBJECT_ID));
        return dataModel;
    }

    private List<IModel.IComicModel> getFRankList(String table, String title, String id)
    {
        List<IModel.IComicModel> models = new ArrayList<>();
        ComicModel model;
        Cursor cursor = mSqlLiteRead.query(table, null, null, null, null, null, null);
        if (cursor.moveToFirst()) {
            do {
                model = new ComicModel();
                model.setTitle(cursor.getString(cursor.getColumnIndex(title)));
                model.setId(cursor.getString(cursor.getColumnIndex(id)));
                models.add(model);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return models;
    }

    public void deleteSearch() {
        mSqlLiteWritable.execSQL("delete from " + ConstFlags.SearchKey.TABLE );
        mSqlLiteWritable.execSQL("delete from " + ConstFlags.SearchHotWords.TABLE );
    }
}
